<?php

namespace app\admin\model;

use think\Model;
use think\Db;
use app\admin\model\Otherconfig;
use app\admin\model\Orderdetail;


class Order extends Model
{


    // 表名
    protected $name = 'order';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'source_text',
        'status_text',
        'create_time_text',
        'pay_time_text',
        'bucket_text',
        'delivery_type_text',
        'delivery_time_text'
    ];
    

   
    public function getSourceList()
    {
        return ['0' => __('Source 0'), '1' => __('Source 1')];
    }

    public function getStatusList()
    {
        return ['0' => '待支付', '1' => '待分配', '2' => '配送中', '3' => '已送达', '4' => '申请退款', '5' => '同意退款','6' => '拒绝退款','7' => '已取消',8 => '已分配'];
    }

    public function getBucketList()
    {
        return ['0' => __('Bucket 0'), '1' => __('Bucket 1')];
    }

    public function getDeliveryTypeList()
    {
        return ['0' => __('Delivery_type 0'), '1' => __('Delivery_type 1')];
    }


    public function getSourceTextAttr($value, $data)
    {
        $value = $value ?: ($data['source'] ?? '');
        $list = $this->getSourceList();
        return $list[$value] ?? '';
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ?: ($data['status'] ?? '');
        $list = $this->getStatusList();
        return $list[$value] ?? '';
    }


    public function getCreateTimeTextAttr($value, $data)
    {
        $value = $value ?: ($data['create_time'] ?? '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getPayTimeTextAttr($value, $data)
    {
        $value = $value ?: ($data['pay_time'] ?? '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getBucketTextAttr($value, $data)
    {
        $value = $value ?: ($data['bucket'] ?? '');
        $list = $this->getBucketList();
        return $list[$value] ?? '';
    }


    public function getDeliveryTypeTextAttr($value, $data)
    {
        $value = $value ?: ($data['delivery_type'] ?? '');
        $list = $this->getDeliveryTypeList();
        return $list[$value] ?? '';
    }


    public function getDeliveryTimeTextAttr($value, $data)
    {
        $value = $value ?: ($data['delivery_time'] ?? '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setCreateTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setPayTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setDeliveryTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }
    public static function caculPrice($orderDetail,$userBuyTicket, $userActiveTicket, $bucket, $active,$ordrId,$deliveryType)
    {
        $total = 0.00;
        if(empty($orderDetail )) return $total;

        $configDetail =  Otherconfig::find(1);
        //没有水桶,加上水桶的押金
        if($bucket == 0) {
            $total +=  $configDetail['bucket'];
        }
        //配送费用
        if( $active == 1) {#如果是活动商品，只能单独购买，结束
            $total +=  $configDetail['peisong'];
            return $total;
        } 
       
        $orderDetail = self::addToOrderDetail( $orderDetail,$ordrId);
       
        if(empty($userBuyTicket) && empty($userActiveTicket)) {//如果没有水票，直接算价格
            foreach($orderDetail['detail'] as $value) {
                if($value['active'] == 1) {
                    $tmpMoney = $value['money'] + $value['delivery_fee'];
                    $total += $tmpMoney;
                }  else {
                    $total += $value['money'];
                }
            }
            if($deliveryType == 1) {//如果是平台送
                $total +=  $configDetail['peisong'];
            }  
            return  $total;
        }
       
        if($userBuyTicket) {#如果使用了自购的水票,这里可以是一张也可以是多张,这里要记录用了是哪张水票
            $ticketIds = explode(',',$userBuyTicket);
            //找出对用的票可以使用的商品
            $list = Db::name('user_ticket_record')->where('id','in',$ticketIds)->field('id,list')->select();
            $tmpList = [];
            foreach($list as $value) {//这个产品可以使用哪些水票
                $tmpList[$value['list']][] = $value['id'];
            }
           
            foreach($orderDetail['detail'] as $value) {//查一下这个产品可以使用多少张票
                $total += $value['money']; //加上原价
                if($value['active'] == 1) {//如果是活动商品,加上运费
                    $total +=  $value['delivery_fee'];
                }
             
                
                 
                   $count =  count($tmpList[$value['detail_id']]);//当前可以使用票的数量
                  
                   if($count > $value['num']) {
                       $total = 0;
                       break;
                   }
                  
                   $detail = Detail::find($value['detail_id']);
                 
                   $total -= $detail['money'] * $count;//减去水票的价格
                  
            }

        } 
        
        if($userActiveTicket) {#只能使用一张
            $ticketIds = explode(',',$userActiveTicket);
            //找出对用的票可以使用的商品
            $list = Db::name('user_ticket_record')->where('id','in',$ticketIds)->field('id,list')->select();
            
            $tmpList = [];
            foreach($list as $value) {//这个产品可以使用哪些水票
                $tmpList[$value['list']][] = $value['id'];
            }
            
            foreach($orderDetail as &$value) {//查一下这个产品可以使用多少张票
                if(empty($value)) continue;
                if(!is_array($value)) continue;
                if(!array_key_exists('detail_id',$value)) continue;
                //$total += $value['money'];//上面已经加过了，这不需要再加
                if(!array_key_exists($value['detail_id'],$tmpList)) continue;
                 $count =  count($tmpList[$value['detail_id']]);//当前可以使用票的数量
                 if($count > $value['num']) {
                     $total = 0;
                     break;
                 }
                 $detail = Detail::find($value['detail_id']);
                 $total -= $detail['money'] *  $count;
          }
        }
        if($deliveryType == 1) {//如果是平台送
            $total +=  $configDetail['peisong'];
        }  
        
        return $total;
    }
  
    public static function addToOrderDetail($detail,$orderId,$type = 0)
    {
        $tmpData = [];
        foreach($detail as $value) {
            if(isset( $tmpData[$value['detail_id']])) {
                $tmpData[$value['detail_id']] += $value['num'];
            } else {
                $tmpData[$value['detail_id']] = $value['num'];
            }
          
        }
         
        $ids = array_column($detail,'detail_id');
        $detail = Detail::where('id','in',implode(',',$ids))->select();
        $insertData = [];
        foreach($detail as $value) {
           
            $insertData[] = [
                'order_sn' =>$orderId,
                'detail_id' => $value['id'],
                'images' => $value['images'],
                'money' => $value['active'] == 0 ? $value['money'] *  $tmpData[$value['id']] :  $value['active_money'] *  $tmpData[$value['id']] ,
                'active' => $value['active'],
                'active_money' => $value['active'],
                'type_id' => $value['type_id'],
                'guige_id' => $value['guige_id'],
                'num' =>   $tmpData[$value['id']],
                'name' => $value['name'],
                'delivery_fee' => $value['delivery_fee'] 
            ];
        }
        if($type == 1) {# =0是
            $model = new Orderdetail();
            $model->saveAll( $insertData);
        }
        
        return  ['detail' => $insertData,'detailId' => implode(',',$ids)];

    }
    public function orderDetail()
    {
        return $this->belongsTo('orderdetail', 'order_id', 'order_sn', [], 'LEFT')->alias('od')->setEagerlyType(0);
    }


    

}
